var express = require('express');
var db = require('../config/db');
var router = express.Router();
var async = require('async');
var libDate = require('../lib/lib_date');
var cache = require('../lib/lib_redis_cache.js');
var md5 = require('md5-node');

/* 关卡 */

/**
 * 获取挂卡列表
 * @param {Object} req
 * @param {Object} res
 * @param {Object} next
 */
router.get('/list', function(req, res, next) {
  //获取关卡列表
  var params = req.query;
  var page = params.page ? params.page : 1;
  var pageSize = params.pageSize ? params.pageSize : 10;
  var offset = (page - 1) * pageSize;
  
  var ck = "checkpoint_list_" + md5(JSON.stringify(params));
  
  console.log("no cache");
  
  //先检查是否存在缓存
  cache.get(ck, (err, data)=>{
    if(data && !params.userId){
      res.json({code : 0, data: data, cache : true});
    } else {
      
      //缓存不存在时， 差数据库
      let where = new Array();
      if(params.userId){
        where.push("`user_id`='" + params.userId + "'");
      }
      if(params.status){
        where.push("`status`='" + params.status + "'");
      }
      
      let sqlCount = "SELECT count(*) as count FROM yx_fkzkw_checkpoint"
      let sql = "SELECT * FROM yx_fkzkw_checkpoint";
      
      if(where.length > 0){
        sqlCount += " WHERE " + where.join(' AND ');
        sql += " WHERE " + where.join(' AND ');
      }
      
      switch(params.order){
        case 'new' : 
          sql += " ORDER BY id DESC";
          break;
        case 'like' : 
          sql += " ORDER BY like_num DESC";
          break;
        default :
          sql += " ORDER BY update_time ASC";
      }
      
      sql += ` limit ${offset}, ${pageSize}`;
      
      //console.log(sqlCount, sql);
      var rList = new Array();
      var rCount = 0;
      
      async.parallel([function(cb){
        //查询行
        db.query(sql, function(err, rows){
          for(let i in rows) {
            let r = rows[i];
            rList.push({
              id : r.id,
              checkpointData : r.checkpoint_data,
              status : r.status,
              likeNum : r.like_num,
              addTime : libDate.time(true, r.add_time)
            })
          }
          cb(null, rList);
        })
      }, function(cb){
        //查询总行数
        db.query(sqlCount, function(err, rows){
          rCount = rows[0]['count'];
          cb(null, rCount);
        })
        
        //cb(null,sqlCount);
      }], function(err, rs){
        //console.log(err, rs);
        var data = {list : rList, total : rCount};
        cache.set(ck, data, 60);
        res.json({code : 0, data: data});
      })
    }
  })
  
  
});



/**
 * 获取挂卡列表
 * @param {Object} req
 * @param {Object} res
 * @param {Object} next
 */
 router.get('/list/v2', function(req, res, next) {
    //获取关卡列表
    var params = req.query;
    var page = params.page ? params.page : 1;
    var pageSize = params.pageSize ? params.pageSize : 10;
    var offset = (page - 1) * pageSize;
    
    var ck = "checkpoint_list_v2" + md5(JSON.stringify(params));
    
    //先检查是否存在缓存
    cache.get(ck, (err, data)=>{
      if(data && !params.userId && params.status != '1'){
        res.json({code : 0, data: data, cache : true});
      } else {
        
        //缓存不存在时， 差数据库
        let where = new Array();
        if(params.userId){
          where.push("`user_id`='" + params.userId + "'");
        }
        if(params.status){
          where.push("`status`='" + params.status + "'");
        }
        
        let sqlCount = "SELECT count(*) as count FROM yx_fkzkw_checkpoint"
        let sql = "SELECT * FROM yx_fkzkw_checkpoint";
        
        if(where.length > 0){
          sqlCount += " WHERE " + where.join(' AND ');
          sql += " WHERE " + where.join(' AND ');
        }
        
        switch(params.order){
          case 'new' : 
            sql += " ORDER BY id DESC";
            break;
          case 'like' : 
            sql += " ORDER BY like_num DESC";
            break;
          default :
            sql += " ORDER BY update_time ASC";
        }
        
        sql += ` limit ${offset}, ${pageSize}`;
        
        //console.log(sqlCount, sql);
        var rList = new Array();
        var rCount = 0;
        
        async.parallel([function(cb){
          //查询行
          db.query(sql, function(err, rows){
            for(let i in rows) {
              let r = rows[i];
              rList.push({
                id : r.id,
                name : r.name,
                status : r.status,
                likeNum : r.like_num,
                addTime : libDate.time(true, r.add_time)
              })
            }
            cb(null, rList);
          })
        }, function(cb){
          //查询总行数
          db.query(sqlCount, function(err, rows){
            rCount = rows[0]['count'];
            cb(null, rCount);
          })
          
          //cb(null,sqlCount);
        }], function(err, rs){
          //console.log(err, rs);
          var data = {list : rList, total : rCount};
          cache.set(ck, data, 60);
          res.json({code : 0, data: data});
        })
      }
    })
});



/**
 * 关卡信息
 * @param {Object} req
 * @param {Object} res
 * @param {Object} next
 */
 router.get('/info', function(req, res, next){
    let params = req.query;
    //判断必要的参数
    if(!params.id){
        res.json({code : 1001, msg : '缺少必要参数id'});
    } else {
      //将数据写入数据库
        sql = "SELECT * FROM `yx_fkzkw_checkpoint` WHERE id=" + params.id;
        db.query(sql, (err, rows) => {
            var row = rows[0];
            var rsData = {
                id: row.id,
                userId: row.user_id,
                name: row.name,
                checkpointData: row.checkpoint_data,
                status: row.status,
                likeNum: row.like_num,
                addTime: libDate.time(true, row.add_time)
            }
            res.json({code : 0, data: rsData});
        })
    }  
});
  


/**
 * 创建关卡
 * @param {Object} req
 * @param {Object} res
 * @param {Object} next
 */
router.post('/create', function(req, res, next){
  let params = req.body;
  //判断必要的参数
  if(!params.userId){
    res.json({code : 1001, msg : '缺少必要参数userId'});
  } else if(!params.checkpointData){
    res.json({code : 1001, msg : '缺少必要参数checkpointData'});
  } else {
    //将数据写入数据库
    const {name} = JSON.parse(params.checkpointData);

    let data = {
      user_id : params.userId,
      name: name,
      checkpoint_data : params.checkpointData,
      add_time : libDate.formatTime('Y-m-d H:i:s'),
      update_time : libDate.formatTime('Y-m-d H:i:s')
    };

    data.status = params.status ? params.status : 1;
    
    db.insert('yx_fkzkw_checkpoint', data, function(err, rows){
      res.json({code : 0, data: {id:rows.insertId}});
    });
  }  
});

/**
 * 修改关卡
 * @param {Object} req
 * @param {Object} res
 * @param {Object} next
 */
router.post('/update', function(req, res, next){
  let params = req.body;
  //判断必要的参数
  if(!params.id){
    res.json({code : 1001, msg : '缺少必要参数id'});
  } else {
    //将数据写入数据库
    let data = {
      update_time : libDate.formatTime('Y-m-d H:i:s'),
    };
    data.status = params.status ? params.status : 1;
    
    if(params.userId){
      data.user_id = params.userId;
    }
    if(params.checkpointData){
      data.checkpoint_data = params.checkpointData;
    }
    
    let where="id=" + params.id;
    db.update('yx_fkzkw_checkpoint', data, where ,function(err, rows){
      res.json({code : 0, data: 'ok'});
    });
  }  
});


/**
 * 喜欢点赞关卡
 * @param {Object} req
 * @param {Object} res
 * @param {Object} next
 */
router.post('/like', function(req, res, next){
  let params = req.body;
  //判断必要的参数
  if(!params.id){
    res.json({code : 1001, msg : '缺少必要参数id'});
  } else {
    num = params.num ? params.num : 1;
    //将数据写入数据库
    let sql="UPDATE `yx_fkzkw_checkpoint` SET `like_num`=`like_num` + " + num + " WHERE `id`=" + params.id;
    
    db.query(sql, function(err, rows){
      res.json({code : 0, data: 'ok'});
    })
  }  
});


/**
 * 修改关卡状态
 * @param {Object} req
 * @param {Object} res
 * @param {Object} next
 */
router.post('/change-status', function(req, res, next){
  let params = req.body;
  //判断必要的参数
  if(!params.id){
    res.json({code : 1001, msg : '缺少必要参数id'});
  } else if(!params.status){
    res.json({code : 1001, msg : '缺少必要参数status'});
  }else {
    //将数据写入数据库
    let where="id=" + params.id;
    
    db.update('yx_fkzkw_checkpoint', {status : params.status}, where ,function(err, rows){
      res.json({code : 0, data: 'ok'});
    });
  }  
});

/**
 * 删除关卡
 * @param {Object} req
 * @param {Object} res
 * @param {Object} next
 */
router.post('/del', function(req, res, next){
  let params = req.body;
  //判断必要的参数
  if(!params.id){
    res.json({code : 1001, msg : '缺少必要参数id'});
  } else {
    //删除数据
    let where="`id`=" + params.id;
    
    let sql = "DELETE FROM `yx_fkzkw_checkpoint` WHERE " + where;
    db.query(sql, function(err, rows){
      res.json({code : 0, data: 'ok'});
    });
  }  
});

module.exports = router;